package com.fanketly.funacg2.ui.viewmodels

import android.util.Log
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.cachedIn
import com.fanketly.funacg2.App
import com.fanketly.funacg2.R
import com.fanketly.funacg2.data.TAG
import com.fanketly.funacg2.data.entity.HistoryEntity
import com.fanketly.funacg2.data.model.FilterMenuItemData
import com.fanketly.funacg2.data.model.WorkList
import com.fanketly.funacg2.data.network.Result
import com.fanketly.funacg2.data.network.flowResult
import com.fanketly.funacg2.data.paging.WorkPagingSource
import com.fanketly.funacg2.data.repo.AudioRepo
import com.fanketly.funacg2.data.repo.HistoryRepo
import com.fanketly.funacg2.data.tFilterMenuList
import com.fanketly.funacg2.ui.viewmodels.state.GlobalState
import com.fanketly.funacg2.ui.viewmodels.state.HomeState
import com.fanketly.funacg2.utils.StringUtils
import com.fanketly.funacg2.utils.getAppString
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class HomeViewModel @Inject constructor(
    private val audioRepo: AudioRepo,
    private val historyRepo: HistoryRepo,
    private val globalStates: GlobalStates,
) : ViewModel() {
    ///////////////////////////////////////////////////////////////////////////
    /*参数区*/
    ///////////////////////////////////////////////////////////////////////////
    private val _homeUiState: MutableState<HomeState> = mutableStateOf(HomeState.Loading)
    val homeUiState
        get() = _homeUiState.value
    val globalState
        get() = globalStates.globalUiState
    var selectedFilterData = mutableStateOf(tFilterMenuList[8])


//    private val _isShowDetail: MutableState<DetailState> = mutableStateOf(DetailState.Loading)
//    val isShowDetail
//        get() = _isShowDetail.value

    //    val homeUiState: StateFlow<HomeState> = loadAll().stateIn(
//        scope = viewModelScope,
//        started = SharingStarted.WhileSubscribed(5_000),
//        initialValue = HomeState.Loading,
//    )

    var isFirstToShowThisTagScreen = true

    private var source: WorkPagingSource? = null

    val pager: Flow<PagingData<WorkList.Work>> = Pager(
        PagingConfig(
            pageSize = 20, initialLoadSize = 20, enablePlaceholders = true, maxSize = 200
        )
    ) {
        source ?: WorkPagingSource(selectedFilterData.value, audioRepo)
    }.flow.cachedIn(viewModelScope)

    ///////////////////////////////////////////////////////////////////////////
    /*方法区*/
    ///////////////////////////////////////////////////////////////////////////
    fun openDrawer() = globalStates.openDrawer()
    fun selectOrder(filterMenuItemData: FilterMenuItemData) {
        if (source == null) {
            source = WorkPagingSource(filterMenuItemData, audioRepo)
        } else if (source!!.filterMenuItemData.name != filterMenuItemData.name) {
            source = WorkPagingSource(filterMenuItemData, audioRepo)
        }
    }

    init {
        Log.i(TAG, "HomeViewModel_init: ")
    }

    /**
     * 获取权限
     * */
    fun reload() {
        viewModelScope.launch {
            audioRepo.getAuth().collect {
                when (it) {
                    is Result.Success -> {
                        App.sToken = it.data.token
                        Log.i(TAG, "getAuth:${App.sToken} ")
                        globalStates.setStateClose()
                    }

                    is Result.Loading -> {
                        globalStates.showLoading()
                    }

                    is Result.Error -> {
                        globalStates.showToast(StringUtils.getFailString(it.exception?.message))
                    }
                }
            }
        }
    }


    /**
     * 获取音声
     * */
    fun getAudio(work: WorkList.Work) {
        viewModelScope.launch {
            flowResult { emit(audioRepo.getAudio(work.id)) }.map {
                when (it) {
                    is Result.Success -> {
                        launch {
                            historyRepo.insert(
                                HistoryEntity(
                                    work.id,
                                    work.title,
                                    work.thumbnailCoverUrl
                                )
                            )
                        }
                        GlobalState.ToDetail(it.data, work)
                    }

                    is Result.Error -> {
                        val message = it.exception?.message ?: ""
                        if (message.contains("Chain validation failed") || message.contains("401")) GlobalState.NotAuthorization
                        else GlobalState.ShowToast(getAppString(R.string.load_failed))
                    }

                    Result.Loading -> GlobalState.Loading
                }
            }.collect {
                globalStates.collectState(it)
            }
        }
    }

    fun setStateClose() = globalStates.setStateClose()

}
